package com.devinlee.designpatterns.observer.mediator;

import com.devinlee.designpatterns.observer.Goods;
import com.devinlee.designpatterns.observer.consumer.MessageListent;

import java.util.*;

/**
 * 观察者模式-店铺消息管理
 * <p>
 * Created by devinlee in 2022.07.04
 */
public class MessageManagement {

    private final Map<String, List<MessageListent>> messageListentMap = Collections.synchronizedMap(new HashMap<>());

    /**
     * 初始化消息类型
     * @param messageTypes
     */
    public MessageManagement(String... messageTypes) {
        for (String messageType : messageTypes) {
            if (!this.messageListentMap.containsKey(messageType)){
                this.messageListentMap.put(messageType, new ArrayList<>());
            }
        }
    }

    /**
     * 订阅
     * @param messageType
     * @param messageListent
     */
    public void subscribe(String messageType, MessageListent messageListent){
        if (!this.messageListentMap.containsKey(messageType)){
            throw new RuntimeException("Event '" + messageType + "' is not registered!");
        }
        this.messageListentMap.get(messageType).add(messageListent);
    }

    /**
     * 退订
     * @param messageType
     * @param messageListent
     */
    public void unsubscribe(String messageType, MessageListent messageListent){
        if (!this.messageListentMap.containsKey(messageType)){
            throw new RuntimeException("Event '" + messageType + "' is not registered!");
        }
        this.messageListentMap.get(messageType).remove(messageListent);
    }

    /**
     * 通知订阅者
     * @param messageType
     * @param goods
     */
    public void call(String messageType, Goods goods){
        if (!this.messageListentMap.containsKey(messageType)){
            throw new RuntimeException("Event '" + messageType + "' is not registered!");
        }
        for (MessageListent messageListent : this.messageListentMap.get(messageType)) {
            messageListent.receive(messageType, goods);
        }
    }
}
